package it.sebsibenal.server;

import it.sebsibenal.client.GreetingService;
import it.sebsibenal.server.dao.SongDAO;
import it.sebsibenal.shared.Operazione;
import it.sebsibenal.shared.Song;

import java.util.List;

import org.apache.log4j.Logger;

/**
 * The server side implementation of the RPC service.
 */
public class GreetingServiceImpl extends BaseService implements GreetingService {

	private static final Logger logger = Logger.getLogger(GreetingServiceImpl.class);
	
	private SongDAO songDAO;
	private MailService mailService;
	
	public String greetServer(String input) throws IllegalArgumentException {
		return "Ok";
	}
	
	@Override
	public List<Song> getSongs() {
		List<Song> songs = songDAO.findAll();
		logger.debug("Recuperati " + songs.size() + " brani");
		return songs;
	}
	
	@Override
	public Song saveSong(Song song, Operazione operazione) {
		if (song.getId()==null) {
			songDAO.insert(song);
			mailService.inviaEmailNuovoBrano(song);
		} else {
			songDAO.update(song);	
			mailService.inviaEmailOperazioneBrano(song, operazione);
		}
		return song;
	}
	
	@Override
	public Song removeYoutubeLink(String link, Song song) {
		song.getYoutubeLinks().remove(link);
		saveSong(song, Operazione.RIMUOVI_VIDEO);
		return song;
	}

	@Override
	public Song addYoutubeLink(String link, Song song) {
		song.getYoutubeLinks().add(link); 
		saveSong(song, Operazione.AGGIUNGI_VIDEO);
		return song;
	}

	@Override
	public Song addComment(String content, Song song) {
		content += "<p style=\"text-align:right\"><b>"+getCurrentUser().getNickname()+"</b> - "+getNow()+"</p>";
		song.getCommenti().add(content);
		saveSong(song, Operazione.AGGIUNGI_COMMENTO);
		return song;
	}

	@Override
	public Song aggiungiCartella(String text) {
		GoogleDocsService gds = new GoogleDocsService();
		gds.createFolder(text);
		return null;
	}
	
	@Override
	public String elencoCartelle() {
		GoogleDocsService gds = new GoogleDocsService();
		return gds.getFolders();
	}

	public void setSongDAO(SongDAO songDAO) {
		this.songDAO = songDAO;
	}

	public void setMailService(MailService mailService) {
		this.mailService = mailService;
	}
	
}
